//
//  GoodsListController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/3.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD

struct GoodsListParameter {
    
    var gc_id : String?
    var keyword : String?
    var priceFrom : String?
    var priceTo : String?
    var key : String?
    var order : String?
    
    init(gc_id : String?,keyword: String?,priceFrom: String?,priceTo: String?,key: String?,order: String?) {
        
        self.gc_id = gc_id
        
        self.keyword = keyword
        
        self.priceFrom = priceFrom
        
        self.priceTo = priceTo
        
        self.key = key
        
        self.order = order


    }
    
    
}

class GoodsListController: BaseViewController {
    
    var keyword : String?
    
    var goodId : String?
    
    var hasmore = "-999"
    
    var dataModels : [HomeItemModel]?
    
    var requestParameter = GoodsListParameter(gc_id: nil, keyword: nil, priceFrom: nil, priceTo: nil, key: nil, order: nil)
    
    var page = -999
    
    lazy var topMenuView : GoodsListTopMenuView = {
    
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: GoodsListTopMenuView.self), owner: nil, options: nil)?.first as! GoodsListTopMenuView
        
        temp.isHidden = true
        
        temp.vc = self
        
        temp.frame = CGRect(x: 0, y: 64, width: KScreenW, height: 36)
        
//        temp.delegate = self
        
        self.view.addSubview(temp)
    
    
        return temp
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNav()
        
        if keyword != nil {
            
            requestParameter.keyword = keyword
        }
        
        if goodId != nil {
            
            requestParameter.gc_id = goodId

        }
        
        
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        plainTableView.tableFooterView = UIView()
        
        plainTableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0)
                
        plainTableView.register(UINib(nibName: StringFromClass(classType: GoodsListCell.self), bundle: nil), forCellReuseIdentifier: GoodsListCell.identifer())
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        
        plainTableView.mj_header.beginRefreshing()
        
        
        plainTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }

        
          // Do any additional setup after loading the view.
    }
    
    
    func setNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .reply, target: self, action: #selector(backBtnDidTap))

        
        let bgView = NavTittleView(frame: CGRect(x: 0, y: 0, width: KScreenW, height: 44))
        
        bgView.backgroundColor = UIColor.clear
        
        let leftBtn = LightDisableBtn(type: .custom)
        
        leftBtn.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
        
        leftBtn.backgroundColor = UIColor.clear
        
        leftBtn.addTarget(self, action: #selector(backBtnDidTap), for: .touchUpInside)
        
        bgView.addSubview(leftBtn)
        
        let btn = LightDisableBtn(type: .custom)
        
        btn.frame = CGRect(x: 50, y: 6, width: KScreenW - 70, height: 32)
        
        btn.setBackgroundImage(UIImage(named: "bg_search_bar_7_gray"), for: .normal)
        
        btn.addTarget(self, action: #selector(tittleBtnDidTap), for: .touchUpInside)
        
        btn.backgroundColor = UIColor.clear
        
        bgView.addSubview(btn)
        
        let label = UILabel()
        
        label.text = seachStr
        
        label.font = UIFont.systemFont(ofSize: 14)
        
        label.textColor = UIColor.colorWith(r: 145, g: 145, b: 145)
        
        label.sizeToFit()
        
        label.frame = CGRect(x: 30, y: 0, width: label.frame.size.width, height: 32)
        
        label.isUserInteractionEnabled = false
        
        btn.addSubview(label)
        
        navigationItem.titleView = bgView
        
        
    }
    
    
    func backBtnDidTap(){
        
        navigationController?.popViewController(animated: true)
        
    }
    
    
    func tittleBtnDidTap(){
        
        let tmepV = SearchController()
        
        
        let nav = BaseNavController(rootViewController: tmepV)
        
        
        present(nav, animated: true, completion: nil)
        
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}


extension GoodsListController{


    func loadData(){
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        if requestParameter.keyword != nil {
            
            parmeter["keyword"] = requestParameter.keyword! as AnyObject
            
        }
        
        if requestParameter.gc_id != nil {
            
            
            parmeter["gc_id"] = requestParameter.gc_id! as AnyObject
            
        }
        
        if requestParameter.key != nil {
            
            parmeter["key"] = requestParameter.key! as AnyObject
            
        }
        
        
        if requestParameter.order != nil {
            
            parmeter["order"] = requestParameter.order! as AnyObject
            
        }
        
        if requestParameter.priceFrom != nil {
            
            parmeter["price_from"] = requestParameter.priceFrom! as AnyObject
            
        }
        
        
        if requestParameter.priceTo != nil {
            
            parmeter["price_to"] = requestParameter.priceTo! as AnyObject
            
        }
        


        addKey = false
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=goods&a=goods_list", parameters: parmeter) { [weak self] (responseObject, error) in
            

            
                if error == nil {
                    
                    self?.hasmore = responseObject!["hasmore"] as! String
                    
                    
                    self?.dataModels = [HomeItemModel]()
                    
                    
                    for dic in responseObject!["datas"]!["goods_list"] as! [[String : AnyObject]]{
                        
                        self!.dataModels!.append(HomeItemModel(dic: dic))
                        
                    }
                    
                    
                    if self!.dataModels!.count > 0{
                        
                        self!.topMenuView.isHidden = false
                        
                    }
                    
                    //                    QL1(self!.dataModels)
                    
                    
                    
                    self!.plainTableView.mj_footer.resetNoMoreData()
                    
                    
                    if self?.hasmore == "0" {
                        
                        self!.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                        
                        
                    }
                    
                    
                    if self!.dataModels!.count == 0{
                        
                        
                        self?.showLogoView(text : "暂无此类商品...")
                        
                        
                    }
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                    
                    self!.plainTableView.reloadData()
                    
                    if self!.dataModels!.count > 0{
                        
                        self!.plainTableView.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .top)
                        
                    }
                    
                    
                }else{
                    
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                    SVProgressHUD.showError(withStatus: error?.domain)
                    
                    
                    
                }
            
        
        
    }
    
}
    
    
    
    func loadMoreData(){
        
        page += 1
        
        
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        
        if requestParameter.keyword != nil {
            
            parmeter["keyword"] = requestParameter.keyword! as AnyObject
            
        }
        
        if requestParameter.gc_id != nil {
            
            
            parmeter["gc_id"] = requestParameter.gc_id! as AnyObject
            
        }
        
        if requestParameter.key != nil {
            
            parmeter["key"] = requestParameter.key! as AnyObject
            
        }
        
        
        if requestParameter.order != nil {
            
            parmeter["order"] = requestParameter.order! as AnyObject
            
        }
        
        if requestParameter.priceFrom != nil {
            
            parmeter["priceFrom"] = requestParameter.priceFrom! as AnyObject
            
        }
        
        
        if requestParameter.priceTo != nil {
            
            parmeter["priceTo"] = requestParameter.priceTo! as AnyObject
            
        }
        
        
        addKey = false

        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=goods&a=goods_list", parameters: parmeter) { [weak self] (responseObject, error) in
            
            
            if error == nil {
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                
                for dic in responseObject!["datas"]!["goods_list"] as! [[String : AnyObject]]{
                    
                    self!.dataModels!.append(HomeItemModel(dic: dic))
                    
                }
                
                
                
                if self?.hasmore == "0" {
                    
                    self!.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }else{
                    
                    self!.plainTableView.mj_footer.endRefreshing()
                    
                }
                
                
                
                
                self!.plainTableView.reloadData()
                
                
            }else{
                
                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
        
        
    }


}


}



extension GoodsListController{



    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return 1
        
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return dataModels?.count ?? 0
        
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let temp = tableView.dequeueReusableCell(withIdentifier: GoodsListCell.identifer()) as! GoodsListCell
        
        temp.model = dataModels?[indexPath.row]
        
        
        return temp
        
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return 90
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if dataModels == nil {
            
            return
        }
        
        let temp = GoodsDetailController()
        
        temp.urlStr = dataModels![indexPath.row].detail_url
        
        navigationController?.pushViewController(temp, animated: true)
        
    }
    
   



}
